import { Platform } from 'react-native';
import RNFS from 'react-native-fs';

const downLoad = (uri: string): Promise<any> => {
  if (!uri) return new Promise((resolve, reject): void => {});

  return new Promise((resolve, reject): void => {
    const dirs =
      Platform.OS === 'ios'
        ? RNFS.LibraryDirectoryPath
        : RNFS.ExternalDirectoryPath; // 外部文件，共享目录的绝对路径（仅限android）
    const downloadDest = `${dirs}/${Math.random() * 10000000}.jpg`;
    const formUrl = uri;
    const options = {
      fromUrl: formUrl,
      toFile: downloadDest,
      background: true
    };

    try {
      const ret = RNFS.downloadFile(options);
      ret.promise
        .then((res): void => {
          resolve(downloadDest);
        })
        .catch((err): void => {
          reject(new Error(err));
        });
    } catch (e) {
      reject(new Error(e));
    }
  });
};

export default downLoad;
